package com.yaowk.web.source.controller;

import com.yaowk.api.file.model.Source;
import com.yaowk.api.file.service.ISourceService;
import com.yaowk.web.system.security.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@RestController
@RequestMapping("/source/file")
@Api(tags = "文件管理")
public class FileController {

    @Autowired
    private ISourceService sourceService;

    @Value("${com.yaowk.web.source.filePath}")
    private String filePath;

    private SimpleDateFormat format = new SimpleDateFormat("/yyyy/mm/dd");

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Source upload(MultipartFile file, Source source) throws IOException {
        String path = format.format(new Date());
        String fileName = file.getName();
        Integer lastPoint = fileName.lastIndexOf(".");
        source.setName(fileName.substring(0, lastPoint));
        fileName = fileName.replace(source.getName(), UUID.randomUUID().toString());
        File saveFile = new File(filePath + path + fileName);
        file.transferTo(saveFile);
        source.setUrl(path + fileName);
        source.setUserId(SecurityUtils.getUserId());

        source = sourceService.simpleSave(source);
        return source;
    }
}
